import { SaveData, GameState, WarehouseState, InventoryItem } from '../types/game';
import { ItemManager } from './itemManager';

const SAVE_KEY = 'soudache_save';
const WAREHOUSE_KEY = 'soudache_warehouse';

// 创建初始仓库状态
const createInitialWarehouse = (): WarehouseState => ({
  items: [],
  capacity: 50,
  upgrades: [],
  coins: 0 // 初始搜币为0
});

// 保存游戏数据到localStorage (单一存档)
export const saveGame = (gameState: GameState, warehouse: WarehouseState): boolean => {
  try {
    const saveData: SaveData = {
      gameState,
      warehouse,
      saveDate: new Date().toISOString(),
    };
    localStorage.setItem(SAVE_KEY, JSON.stringify(saveData));
    return true;
  } catch (error) {
    console.error('Failed to save game:', error);
    return false;
  }
};

// 从localStorage加载游戏数据
export const loadGame = (): SaveData | null => {
  try {
    const data = localStorage.getItem(SAVE_KEY);
    if (data) {
      return JSON.parse(data) as SaveData;
    }
    return null;
  } catch (error) {
    console.error('Failed to load game:', error);
    return null;
  }
};

// 检查是否有存档
export const hasSaveData = (): boolean => {
  return localStorage.getItem(SAVE_KEY) !== null;
};

// 保存仓库数据
export const saveWarehouse = (warehouse: WarehouseState): boolean => {
  try {
    localStorage.setItem(WAREHOUSE_KEY, JSON.stringify(warehouse));
    return true;
  } catch (error) {
    console.error('Failed to save warehouse:', error);
    return false;
  }
};

// 加载仓库数据
export const loadWarehouse = (): WarehouseState => {
  try {
    const data = localStorage.getItem(WAREHOUSE_KEY);
    if (data) {
      return JSON.parse(data) as WarehouseState;
    }
    return createInitialWarehouse();
  } catch (error) {
    console.error('Failed to load warehouse:', error);
    return createInitialWarehouse();
  }
};

// 向仓库添加物品
export const addItemToWarehouse = (item: InventoryItem): boolean => {
  try {
    const warehouse = loadWarehouse();
    const existingItemIndex = warehouse.items.findIndex(warehouseItem => warehouseItem.id === item.id);
    
    if (existingItemIndex >= 0) {
      // 如果物品已存在，增加数量
      warehouse.items[existingItemIndex].quantity += item.quantity;
    } else {
      // 检查仓库容量
      if (warehouse.items.length >= warehouse.capacity) {
        console.error('Warehouse is full');
        return false;
      }
      // 添加新物品
      warehouse.items.push({ ...item });
    }
    
    return saveWarehouse(warehouse);
  } catch (error) {
    console.error('Failed to add item to warehouse:', error);
    return false;
  }
};

// 从仓库移除物品
export const removeItemFromWarehouse = (itemId: string, quantity: number = 1): boolean => {
  try {
    const warehouse = loadWarehouse();
    const itemIndex = warehouse.items.findIndex(item => item.id === itemId);
    
    if (itemIndex >= 0) {
      warehouse.items[itemIndex].quantity -= quantity;
      if (warehouse.items[itemIndex].quantity <= 0) {
        warehouse.items.splice(itemIndex, 1);
      }
      return saveWarehouse(warehouse);
    }
    return false;
  } catch (error) {
    console.error('Failed to remove item from warehouse:', error);
    return false;
  }
};



// 出售物品并获得搜币
export const sellItemFromWarehouse = (itemId: string, quantity: number = 1): number => {
  try {
    const warehouse = loadWarehouse();
    const itemIndex = warehouse.items.findIndex(item => item.id === itemId);
    
    if (itemIndex >= 0) {
      const item = warehouse.items[itemIndex];
      if (!item.sellable) {
        console.error('Item is not sellable');
        return 0;
      }
      
      const sellQuantity = Math.min(quantity, item.quantity);
      const itemValue = ItemManager.getItemValue(item);
      const earnedCoins = itemValue * sellQuantity;
      
      // 减少物品数量
      warehouse.items[itemIndex].quantity -= sellQuantity;
      if (warehouse.items[itemIndex].quantity <= 0) {
        warehouse.items.splice(itemIndex, 1);
      }
      
      // 增加搜币
      warehouse.coins += earnedCoins;
      
      if (saveWarehouse(warehouse)) {
        return earnedCoins;
      }
    }
    return 0;
  } catch (error) {
    console.error('Failed to sell item from warehouse:', error);
    return 0;
  }
};


